import axios from 'axios'
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
Vue.use(VueRouter)


const routes = [
  { 
    path: '/', 
    redirect: '/home', 
    name: 'index', 
    component: () => import('../views/Index.vue'),
    children: [
      { path: 'home', name: 'home', component: () => import('../views/Home/Home.vue')},
      { path: 'goods', name: 'home', component: () => import('../views/Goods/Goods.vue')},
      { path: 'thanks', name: 'home', component: () => import('../views/Thanks/Thanks.vue')},
      { path: 'goodsDetail/:id', name: 'goodsDetail', component: () => import('../views/GoodsDetail/GoodsDetail.vue'), props: true, }
    ]
  },

  { 
    path: '/login', 
    name: 'login', 
    component: () => import('../views/Login/Login.vue')
  },

  {
    path: '/user',
    name: 'user',
    component: () => import('../views/User/User.vue'),
    meta:{
      auth: true
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

router.beforeEach((to, from, next) => {
  axios.post('/api/validate', {}).then(res => {
    const data = res.data
    if(data.state !== 1 ) {
      if(to.meta.auth){
        next('/login')
      } else {
        next()
      }
    } else {
      store.commit('ISLOGIN', data)
    }
  })

  next()
})

export default router
